package com.sunchp.jsondb;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class JsonDBTemplate {
    private String dbFileLocationString;
    private Map<String, CollectionMetaData> collections;

    public JsonDBTemplate(String dbFileLocationString) {
        this.dbFileLocationString = dbFileLocationString;
        this.collections = JsonReader.readObject(this.dbFileLocationString);
    }

    public Set<String> getCollectionNames() {
        return this.collections.keySet();
    }

    public boolean collectionExists(String collectionName) {
        return this.collections.keySet().contains(collectionName);
    }

    public <T> List<T> findAll(String collectionName, Class<T> entityClass) {
        CollectionMetaData collectionMetaData = this.collections.get(collectionName);
        if (collectionMetaData == null) {
            throw new JsonDBException("Collection by name '" + collectionName + "' not found. Create collection first.");
        }

        return collectionMetaData.toJavaList(entityClass);
    }

    public <T> T findByIndex(int index, String collectionName, Class<T> entityClass) {
        CollectionMetaData collectionMetaData = this.collections.get(collectionName);
        if (collectionMetaData == null) {
            throw new JsonDBException("Collection by name '" + collectionName + "' not found. Create collection first.");
        }

        return collectionMetaData.get(index, entityClass);
    }
}
